package com.mall.shopping.services;

import com.alibaba.druid.sql.visitor.functions.If;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: mjm
 * @Date: 2021/12/13
 * @Time: 19:21
 * @Description:
 */

@Slf4j
@Component
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;
    //


    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();

        try {
            //检验参数
            request.requestCheck();
            //不同的用户对应的购物车的key为userId
            Long userId = request.getUserId();
            //long类型转换为string类型
            //这一步可以理解是给map取了个名字"userId" 我们到其他地方可以用这个名字调出这个map
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            //获取所有value，以collection返回
            List<CartProductDto> cartProductDtoArrayList = map.get(userId);
            cartListByIdResponse.setCartProductDtos(cartProductDtoArrayList);
            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            cartListByIdResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return cartListByIdResponse;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();

        try {
            Long userId = request.getUserId();
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            List<CartProductDto> cartProductDtos1 = map.get(userId);
            if (cartProductDtos1 == null) {
                map.put(userId, new ArrayList<CartProductDto>());
            }
            List<CartProductDto> cartProductDtos = map.get(userId);
            CartProductDto cartProductDto = new CartProductDto();
            //根据商品id查询商品具体信息
            Item item = itemMapper.selectByPrimaryKey(request.getProductId());

            //老师的前端代码默认为选中状态，实际上应该为未选中，所以设置为false
            cartProductDto.setChecked("false");
            cartProductDto.setLimitNum(item.getLimitNum().longValue());
            cartProductDto.setProductImg(item.getImage());
            cartProductDto.setSalePrice(item.getPrice());
            cartProductDto.setProductName(item.getTitle());
            cartProductDto.setProductId(request.getProductId());
            cartProductDto.setProductNum(request.getProductNum().longValue());
            //过滤出商品id的list
            List<CartProductDto> collect = cartProductDtos.stream().filter(s -> s.getProductId().equals(request.getProductId())).collect(Collectors.toList());
            //如果为空,证明当前购物车中没有这个商品,在集合中添加即可
            if (CollectionUtils.isEmpty(collect)) {
                cartProductDtos.add(cartProductDto);
            } else {
                //stream流forEach
                cartProductDtos.forEach(s -> {
                    if (s.getProductId().equals(request.getProductId())) {
                        s.setProductNum(s.getProductNum() + request.getProductNum());
                    }
                });
//                for (CartProductDto productDto : cartProductDtos) {
//                    if (productDto.getProductId().equals(request.getProductId())) {
//                        productDto.setProductNum(productDto.getProductNum() + request.getProductNum());
//                    }
//                }
            }
            //将商品加入购物车
            map.put(userId, cartProductDtos);
            //返回response
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            addCartResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            addCartResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }

        return addCartResponse;
    }


    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        Long userId = request.getUserId();
        Long itemId = request.getItemId();
        Integer num = request.getNum();
        String checked = request.getChecked();

        try {
            request.requestCheck();
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            List<CartProductDto> cartProductDtos = map.get(userId);
            //stream流forEach
            cartProductDtos.stream().forEach(s -> {
                if (s.getProductId().equals(itemId)) {
                    s.setProductNum(Long.valueOf(num.toString()));
                    s.setChecked(checked);
                }
            });
            //遍历
//            for (CartProductDto cartProductDto : cartProductDtos) {
//                if (cartProductDto.getProductId().equals(itemId)) {
//                    cartProductDto.setChecked(checked);
//                    cartProductDto.setProductNum(Long.valueOf(num.toString()));
//                }
//            }
            map.put(userId, cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("updateCartNum Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        Long userId = request.getUserId();
        String checked = request.getChecked();


        try {
            request.requestCheck();
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            List<CartProductDto> cartProductDtos = map.get(userId);
            cartProductDtos.stream().forEach(s -> s.setChecked(checked));
            map.put(userId, cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("checkAllCartItem Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        Long itemId = request.getItemId();
        Long userId = request.getUserId();

        try {
            request.requestCheck();
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            List<CartProductDto> cartProductDtos = map.get(userId);
            List<CartProductDto> collect = cartProductDtos.stream().filter(s -> !s.getProductId().equals(itemId)).collect(Collectors.toList());
            map.put(userId, collect);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());


        } catch (Exception e) {
            log.error("deleteCartItem Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        Long userId = request.getUserId();

        try {
            request.requestCheck();
            RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());
            List<CartProductDto> cartProductDtos = map.get(userId);
            List<CartProductDto> collect = cartProductDtos.stream().filter(s -> "false".
                    equals(s.getChecked())).collect(Collectors.toList());
            map.put(userId, collect);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("deleteCheckedItem Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {


        return null;
    }
}
